import {messages} from "share/common";
import React from 'react'
import { Form, Input, Button, message, Row, Col, DatePicker, InputNumber } from 'antd'
const FormItem = Form.Item;
const { TextArea } = Input;
import moment from 'moment'
import Location from 'components/location'
import mileageExpenseService from 'containers/mileage-subsidy-expense/mileage-subsidy-expense.service'
import 'styles/mileage-subsidy-expense/mileage-subsidy-expense.scss'
import { MD5 } from 'share/common';
import config from 'config'
import WayPoint from './components/way-point';
import configureStore from 'stores/index';

class NewSubsidy extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      record: null,
      loading: false,
      isNew: true,
      start: null,
      end: null,
      actualMileage: 0,
      referenceMileage: 0
    }
  }

  componentWillReceiveProps(nextProps) {
    if(!nextProps.params || nextProps.params == this.props.params) return
    this.props.form.resetFields();
    if(nextProps.params.record && this.state.record !== nextProps.params.record) { //编辑
      let params = nextProps.params;
      this.setState({
        record: params.record,
        isNew: params.record.isNew
      }, () => {this.props.form.setFieldsValue({ viaPoints: params.record.viaPoints || [] });})
    } else if (!nextProps.params.record) {
      this.setState({
        isNew: nextProps.params.isNew,
        record: null
      })
    }
  }

  onCancel = () => {
    this.props.form.resetFields();
    this.props.close();
    this.props.onClose();
  };

  startLocationChange = value =>{
    if (!value || !JSON.parse(value).address) {
      this.setState({ start: null });
      return;
    }
    this.setState({ start: value },() => {
      if(this.state.end){
        this.getDrivingDistance()
      }
    })
  };

  endLocationChange = value => {
    if (!value || !JSON.parse(value).address) {
      this.setState({ end: null });
      return;
    }
    this.setState({ end: value },() => {
      if(this.state.start){
        this.getDrivingDistance()
      }
    })
  };

  //得到上下车地点之间的导航距离
  getDrivingDistance() {
    const { start, end } = this.state;
    const to = `${JSON.parse(end).latitude},${JSON.parse(end).longitude}`;
    const from = `${JSON.parse(start).latitude},${JSON.parse(start).longitude}`;
    const tenantMode = configureStore.store.getState().main.tenantMode;
    const sig = MD5(`/ws/direction/v1/driving/?from=${from}&key=${config.tencentMapKey}${tenantMode ? '&roleType=TENANT' : ''}&to=${to}${config.tencentSecretKey}`);
    const params = {
      to,
      key: config.tencentMapKey,
      from,
      sig
    };
    tenantMode && (params.roleType = 'TENANT');
    mileageExpenseService.getDistance(params)
      .then(response => {
        if (response.status === 200 && response.data.result) {
          let distance = (response.data.result.routes[0].distance / 1000).toFixed(2);
          this.setState({ actualMileage: distance, referenceMileage: distance });
          this.props.form.setFieldsValue({ mileage: distance, referenceMileage: distance });
        } else {
          message.error(response.data.message);
        }
      });
  }

  //提交
  handleSubmit = e => {
    const { isNew,record } = this.state;
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err,values) => {
      if(!err){
        const flag = (values.viaPoints || []).some(item => {
          if (item.arrivalTime.valueOf() < values.departTime.valueOf() || item.arrivalTime.valueOf() > values.arriveTime.valueOf()) {
            return true;
          }
        });
        values.departTime = moment(values.departTime).format('YYYY-MM-DD HH:mm:ss')
        values.arriveTime = moment(values.arriveTime).format('YYYY-MM-DD HH:mm:ss');
        if (moment(values.arriveTime)
          .isBefore(values.departTime)) {
          message.error(messages('mileage-subsidy-expense.key71')/*下车时间不能早于上车时间*/);
          return;
        }
        if (flag) {
          message.error(messages('mileage-subsidy-expense.key72')/*途径时间必须在上车时间和下车时间之间*/);
          return;
        }
        values.start = JSON.parse((values.start).replace(/address/g,"place").replace(/longitude/g,"lng").replace(/latitude/g,"lat"));
        values.end = JSON.parse((values.end.replace(/address/g,"place").replace(/longitude/g,"lng").replace(/latitude/g,"lat")));
        values.viaPoints = (values.viaPoints || []).filter(item => !!item.lat);
          this.setState({ loading: true });
          if (isNew) {
            this.newMileageSubsidy(values)
          } else {
            values.id = record.id;
            this.editMileageSubsidy(values)
          }
      }
    })
  };

  //新建里程补贴
  newMileageSubsidy(values) {
    mileageExpenseService.addOrders(values).then( response => {
      if (response.status === 200) {
        this.setState({ loading: false, end: null, start : null });
        message.success(`${messages('common.save.success',{name:""})}`);
        this.props.form.resetFields();
        this.props.close(true)
      }
    }).catch(e => {
      this.setState({ loading: false });
      message.error(`${messages('common.save.filed')}, ${e.response.data.message}`)
    });
  }

  //编辑里程补贴
  editMileageSubsidy(values){
    mileageExpenseService.updateOrder(values).then(response => {
      if (response.status === 200) {
        this.setState({ loading: false, end: null, start : null });
        message.success(`${messages('common.save.success',{name:""})}`);
        this.props.form.resetFields();
        this.props.close(true)
      }
    }).catch(e => {
      this.setState({ loading: false });
      message.error(`${messages('common.save.filed')}, ${e.response.data.message}`)
    });
  }

  //删除订单
  deleteOrder = ()=>{
    mileageExpenseService.deleteOrder(this.state.record.id).then(response => {
      if (response.status === 200){
        this.setState({ loading: false });
        message.success(messages('common.delete.success',{ name:'' }));
        this.props.form.resetFields();
        this.props.close(true)
      }
    }).catch(() => {
      this.setState({ loading: false });
      message.error(messages('common.operate.filed'));
    })
  };

  getStartPlace = start => {
    return `{"address":"${start.place}","longitude":${start.lng},"latitude":${start.lat}}`
  };

  getEndPlace = end => {
    return `{"address":"${end.place}","longitude":${end.lng},"latitude":${end.lat}}`
  };

  handleViaPoints = (viaPoints) => {
    this.props.form.setFieldsValue({ viaPoints });
  };

  handleViaPointsValidator = (rule, value, callback) => {
    if(value){
      value.map(item => {
        if (!item.arrivalTime && item.place || item.arrivalTime && !item.place) {
          callback(messages('mileage-subsidy-expense.key69')/*请填写完整*/)
        }
      })
    }
    callback();
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { record, isNew } = this.state;
    return (
      <div>
        <Form onSubmit={this.handleSubmit}>
          <Row>
            <Col span={11}>
              <FormItem  label={messages('mileage-subsidy-expense.key19'/*上车时间*/)}>
                {getFieldDecorator('departTime', {
                  rules: [{
                    required: true,
                    message: messages('mileage-subsidy-expense.key38'/*请输入上车时间*/)
                  }],
                  initialValue: record ? moment(record.departTime) : moment()
                })(
                  <DatePicker  format="YYYY-MM-DD HH:mm" showTime style={{ width:'95%' }}/>
                  )
                }
              </FormItem>
            </Col>
            <Col span={11}>
              <FormItem  label={messages('mileage-subsidy-expense.key20'/*上车地点*/)}>
                {getFieldDecorator('start', {
                  rules: [
                    {
                      required: true,
                      message: messages('mileage-subsidy-expense.key39'/*请输入上车地点*/)
                    },
                    {
                      validator: (item, value, callback) => {
                        if (value && !JSON.parse(value).address) {
                          callback(messages('mileage-subsidy-expense.key39'));
                        }
                        callback();
                      }
                    }],
                  initialValue: record ? this.getStartPlace(record.start) : ''
                })(
                  <Location onChange={this.startLocationChange}/>
                  )
                }
              </FormItem>
            </Col>
          </Row>
          <FormItem>
            {getFieldDecorator('viaPoints', {
              rules: [{ validator: this.handleViaPointsValidator }]
            })(
              <WayPoint onchange={this.handleViaPoints}/>
            )}
          </FormItem>
          <Row>
            <Col span={11}>
              <FormItem label={messages('mileage-subsidy-expense.key21'/*下车时间*/)}>
                {getFieldDecorator('arriveTime', {
                  rules: [{
                    required: true,
                    message: messages('mileage-subsidy-expense.key40'/*请输入下车时间*/)
                  }],
                  initialValue: record ? moment(record.arriveTime) : moment()
                })(
                  <DatePicker showTime format="YYYY-MM-DD HH:mm" style={{width:'95%'}}/>
                  )
                }
              </FormItem>
            </Col>
            <Col span={11}>
              <FormItem label={messages('mileage-subsidy-expense.key22'/*下车地点*/)}>
                {getFieldDecorator('end', {
                  rules: [
                    {
                      required: true,
                      message: messages('mileage-subsidy-expense.key41'/*请输入下车地点*/)
                    },
                    {
                      validator: (item, value, callback) => {
                        if (value && !JSON.parse(value).address) {
                          callback(messages('mileage-subsidy-expense.key41'/*请输入下车地点*/));
                        }
                        callback();
                      }
                    }],
                  initialValue: record ? this.getEndPlace(record.end) : ''
                })(
                  <Location onChange={this.endLocationChange}/>
                  )
                }
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={11}>
              <FormItem label={messages('mileage-subsidy-expense.key23'/*实际里程(KM)*/)}>
                {getFieldDecorator('mileage', {
                  rules: [{
                    required: true,
                    message: messages('mileage-subsidy-expense.key42'/*请输入实际里程*/)
                  }],
                  initialValue: record ? record.mileage : ''
                })(
                  <InputNumber style={{ width:'95%' }}  size="middle" min={0} precision={2} />
                  )
                }
              </FormItem>
            </Col>
            <Col span={11}>
              <FormItem label={messages('mileage-subsidy-expense.key43'/*参考里程(KM)*/)}>
                {getFieldDecorator('referenceMileage', {
                  initialValue: record ? record.referenceMileage : ''
                })(
                  <InputNumber
                    min={0}
                    size="middle"
                    style={{ width: '100%' }}
                    disabled
                    precision={2}
                    placeholder={messages('mileage-subsidy-expense.key70')/*输入出发目的地点后自动计算*/}/>
                )
                }
              </FormItem>
            </Col>
          </Row>
          <FormItem label={messages('mileage-subsidy-expense.key6'/*事由说明*/)}>
            {getFieldDecorator('remark', {
              initialValue: record ? record.remark : ''
            })(
              <TextArea autosize={{ minRows: 2 }}
                        style={{ minWidth:'100%' }}
                        placeholder={messages('common.please.enter')/*请输入*/}/>
              )
            }
          </FormItem>
          <div className="slide-footer">
            {!isNew && <Button type="danger" className='danger-button' onClick={this.deleteOrder}>{messages('common.delete')}</Button>}
            <Button type="primary" htmlType="submit">{messages('common.save')}</Button>
            <Button onClick={this.onCancel}>{messages('common.cancel')}</Button>
          </div>
        </Form>
      </div>
    )
  }
}

const wrappedNewSubsidy = Form.create()(NewSubsidy)
export default wrappedNewSubsidy

